package top.wangjingxin.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import top.wangjingxin.base.Result;
import top.wangjingxin.dao.RotationDao;
import top.wangjingxin.model.link.RotationVO;
import top.wangjingxin.util.DeleteUtil;
import top.wangjingxin.util.UuidUtil;

import java.io.File;
import java.io.IOException;

import static top.wangjingxin.cache.ResultCache.*;
import static top.wangjingxin.config.AppConfig.ROOT;

@Service
public class RotationService {

    @Autowired
    RotationDao rotationDao;

    public Result get() {
        return getDataOk(rotationDao.get());
    }

    public Result delete(String id) {
        if(rotationDao.delete(id)==1){
            DeleteUtil.delete(id);
            return OK;
        }
        return FAILURE;
    }

    @Transactional
    public Result add(MultipartFile file, RotationVO rotationVO) {
        String id = UuidUtil.Uuid();
        try {
            file.transferTo(new File(ROOT + File.separator + "resource" + File.separator + id));
            rotationVO.setId(id);
            rotationDao.insert(rotationVO);
        } catch (IOException e) {
            e.printStackTrace();
            return FAILURE;
        }
        return getDataOk(id);
    }
}
